package com.purong.purong.fragment;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.PuRongApp;
import com.purong.purong.R;
import com.purong.purong.bean.LoginBean;
import com.purong.purong.util.CommonUtil;
import com.yao.sdk.net.ResponseInfo;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zengwenjie on 2017/11/30.
 */
public class LoginSmsFragment extends BaseFragment {
    private EditText phoneEd,verEd;
    private View phoneLine,verLine;
    private TextView getCode;
    private ImageView phoneClear,verClear;
    private Button loginBtn;
    private boolean phoneInput,verInput;
    private boolean canGetValid=true;
    private int timeCount=-1;
    @Override
    public int getRootViewId() {
        return R.layout.login_sms_fragment;
    }

    @Override
    public void initView(View rootView) {
        phoneLine=(View)rootView.findViewById(R.id.phone_cut_line);
        verLine=(View)rootView.findViewById(R.id.ver_cut_line);
        phoneEd=(EditText)rootView.findViewById(R.id.phone_ed);
        verEd=(EditText)rootView.findViewById(R.id.verification_ed);
        getCode=(TextView)rootView.findViewById(R.id.get_code);
        getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!canGetValid)
                    return;
                if (phoneEd.getText().toString().trim().equals("")) {
                    showToast("请输入手机号");
                    return;
                }
                if (!CommonUtil.isPhoneNum(phoneEd.getText().toString().trim())) {
                    showToast("请输入正确的手机号");
                    return;
                }
                getCode(phoneEd.getText().toString());
            }
        });
        phoneClear=(ImageView)rootView.findViewById(R.id.phone_clear);
        phoneClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneEd.setText("");
            }
        });
        verClear=(ImageView)rootView.findViewById(R.id.ver_clear);
        verClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verEd.setText("");
            }
        });
        loginBtn=(Button)rootView.findViewById(R.id.login);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (phoneEd.getText().toString().trim().equals("")) {
                    showToast("请输入手机号");
                    return;
                }
                if (!CommonUtil.isPhoneNum(phoneEd.getText().toString().trim())) {
                    showToast("请输入正确的手机号");
                    return;
                }
                if (verEd.getText().toString().trim().equals("")){
                    showToast("请输入验证码");
                    return;
                }
                smsLogin(phoneEd.getText().toString().trim(),verEd.getText().toString().trim());
            }
        });
        phoneEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().equals("")) {
                    phoneInput = false;
                    phoneClear.setVisibility(View.GONE);
                } else {
                    phoneInput = true;
                    phoneClear.setVisibility(View.VISIBLE);
                }
                if (phoneInput && verInput) {
                    loginBtn.setBackgroundResource(R.drawable.button_blue_radius5);
                } else {
                    loginBtn.setBackgroundResource(R.drawable.button_gray_radius5);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        verEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().equals("")) {
                    verInput = false;
                    verClear.setVisibility(View.GONE);
                } else {
                    verInput = true;
                    verClear.setVisibility(View.VISIBLE);
                }
                if (phoneInput && verInput) {
                    loginBtn.setBackgroundResource(R.drawable.button_blue_radius5);
                } else {
                    loginBtn.setBackgroundResource(R.drawable.button_gray_radius5);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        phoneEd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    phoneLine.setBackgroundColor(getActivity().getResources().getColor(R.color.blue));
                } else {
                    phoneLine.setBackgroundColor(getActivity().getResources().getColor(R.color.cut_line));
                }
            }
        });
        verEd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    verLine.setBackgroundColor(getActivity().getResources().getColor(R.color.blue));
                } else {
                    verLine.setBackgroundColor(getActivity().getResources().getColor(R.color.cut_line));

                }
            }
        });
    }
    private void getCode(String phone){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("phone",phone);
        canGetValid=!request(Contant.SMS, params, true,true);
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==-1){
                getCode.setTextColor(getResources().getColor(R.color.blue));
                getCode.setText("获取验证码");
                canGetValid=true;
            }else {
                getCode.setText("重新获取"+"("+msg.what+")秒");
            }
        }
    };
    public void countDown(){
        timeCount=60;
        getCode.setTextColor(getResources().getColor(R.color.text_gray));
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timeCount--;
                handler.sendEmptyMessage(timeCount);
                if (timeCount==-1){
                    this.cancel();
                }
            }
        },0,1000);
    }
    private void smsLogin(String phone,String verification){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("user_phone",phone);
        params.put("user_verification",verification);
        request(Contant.SMS_LOGIN, params, true,true);
    }
    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.SMS)){
            if (responseInfo.isRequestOk){
                showToast("验证码已发送");
                countDown();
            }else {
                canGetValid=true;
            }
        }else if (responseInfo.url.equals(Contant.SMS_LOGIN)){
            if (responseInfo.isRequestOk){
                try{
                    LoginBean loginBean= JSON.parseObject(responseInfo.content,LoginBean.class);
                    loginBean.setPwd("");
                    loginBean.save(getActivity());
                    JPushInterface.setAlias(getActivity(),0,loginBean.getUser_id());
                    showToast("登录成功");
                    getActivity().finish();
                }catch (Exception e){

                }
            }

        }
    }
    @Override
    public void initData() {

    }
}
